const ExtractTextPlugin = require('extract-text-webpack-plugin')
const BaseModules = require('../BaseModules')
const { resolve, exists } = require('../../helper')
const { cssLoader, otherLoader } = require('./baseLoader')

const extractLoader = function(use, type){
	if(type === 'CommonLoaders'){
		return ExtractTextPlugin.extract({
			use, fallback: 'vue-style-loader'
		})
	}
	return BaseModules.command.dev ? 
	[{loader:'style-loader',options:{singleton:true}}].concat(use) : 
	ExtractTextPlugin.extract({
		use, fallback: 'vue-style-loader'
	})
}


const generateSassResourceLoader = function(type){
	const use = [...cssLoader,'sass-loader']
	if(BaseModules.appConf.sassResources){
		use.push(
			{
				loader: 'sass-resources-loader',
				options: {
					resources: [resolve(BaseModules.appConf.sassResources)]
				}
			}
		)
	}
	return extractLoader(use, type)
}

const generateLoaders = function(type){
	const loaders = loader => {
		const use = [...cssLoader]
		if(loader){
			const _loader = {
				loader: loader + '-loader',options: { sourceMap: false }
			}

			if(loader == 'stylus'){
				_loader.options.import = [resolve(BaseModules.appConf.src,'common/components/theme.styl')]
			}

			use.push(_loader)
		}
		return extractLoader(use, type)
	}
	return {
		css: loaders(),
		less: loaders('less'),
		sass: generateSassResourceLoader(type),
		scss: generateSassResourceLoader(type),
		styl: loaders('stylus'),
		stylus: loaders('stylus')
	}
}


exports.CommonLoaders = function(){
	const loader = [...otherLoader]
	const _generateLoaders = generateLoaders('CommonLoaders')
	for(let extension in _generateLoaders){
		const use = _generateLoaders[extension]
		loader.push({
			test: new RegExp('\\.' + extension + '$'),
			use
		})
	}
	return loader
}

exports.NormalLoaders = function(){
	const loader = [...otherLoader]

	if(BaseModules.appConf.beforeHtmlParse){
		loader.push({
			resourceQuery: /^\?vue&type=template/,
			loader: resolve(__dirname, '../../loader/sfc-loader/template-loader')
		})
	}

	if(BaseModules.appConf.beforeJsparse){
		loader.push({
			resourceQuery: /^\?vue&type=script/,
			loader: resolve(__dirname, '../../loader/sfc-loader/script-loader')
		})
	}

	const _generateLoaders = generateLoaders('NormalLoaders')
	for(let extension in _generateLoaders){
		const use = _generateLoaders[extension]
		loader.push({
			test: new RegExp('\\.' + extension + '$'),
			use
		})
	}
	return loader
}
